# -*- coding: utf-8 -*-

from odoo import models, api, fields
from odoo.exceptions import UserError, ValidationError

from ..utils.random import Random


class User(models.Model):
    _name = 'exhibition.users'
    _inherits = {
        'res.users': 'res_user_id'
    }

    appadmin = fields.Boolean(string='APP管理员', default=False)
    admin = fields.Boolean(string='管理员', default=False)
    editor = fields.Boolean(string='编辑', default=False)
    salesman = fields.Boolean(string='销售', default=False)
    salesman_no = fields.Char(string='销售编号', default='')
    res_user_id = fields.Many2one(
        'res.users',
        required=True,
        ondelete='cascade',
    )
    department = fields.Many2one(
        'exhibition.department',
        string='所属部门',
    )

    @api.model_create_multi
    def create(self, vals):
        self = self.sudo()
        # vals['groups_id'] = [[6, False, [self.env.ref('')]]]
        role = self.env.context.get('role', '')
        for val in vals:
            getattr(self, '_prepare_for_{}'.format(role), None) and getattr(self, '_prepare_for_{}'.format(role))(val)
        user = super(User, self).create(vals)
        return user

    @api.constrains('salesman', 'salesman_no')
    def check_salesman_no(self):
        if not self.salesman:
            return
        if not self.salesman_no:
            raise ValidationError('请为销售设置销售编号')
        salesmen = self.search([('salesman', '=', True)])
        for salesman in salesmen:
            if self.id != salesman.id and self.salesman_no == salesman.salesman_no:
                raise ValidationError('指定销售编号已存在，请重新设置')
        if not self.department:
            raise ValidationError('请为销售设置部门')

    def _prepare_for_role(self, vals):
        main_company = self.env.ref('base.main_company')
        vals['company_id'] = main_company.id
        vals['company_ids'] = [[6, False, main_company.ids]]
        vals['tz'] = 'Asia/Shanghai'

    def _prepare_for_editor(self, vals):
        self._prepare_for_role(vals)
        vals['editor'] = True
        vals['groups_id'] = [(6, 0, [self.env.ref('exhibition.editors_group').id])]

    def _prepare_for_salesman(self, vals):
        self._prepare_for_role(vals)
        salesman_no = vals['salesman_no']
        vals['salesman'] = True
        vals['login'] = salesman_no + '-' + Random.string()
        if 'name' not in vals:
            vals['name'] = salesman_no
        vals['groups_id'] = [(6, 0, [self.env.ref('exhibition.sales_group').id])]

    def exhibition_change_password(self):
        return {
            'type': 'ir.actions.client',
            'tag': 'change_password',
            'target': 'new',
        }

    @api.multi
    def exhibition_reset_password(self):
        self.ensure_one()

        active_model = self.env.context.get('active_model')
        if not active_model:
            return False
        active_ids = self.env.context.get('active_ids')
        if not active_ids:
            return False
        active_user = self.env['exhibition.users'].browse(active_ids)
        if not active_user:
            return False
        active_user.ensure_one()
        res = self.env['exhibition.reset_user_password_wizard'].create({
            'user_id': active_user.id,
            'name': active_user.name,
            'login': active_user.login,
        })
        return {
            'type': 'ir.actions.act_window',
            'name': '重置密码',
            'res_model': 'exhibition.reset_user_password_wizard',
            'view_id': self.env.ref('exhibition.reset_user_password_wizard_view').id,
            'res_id': res.id,
            'view_type': 'form',
            'view_mode': 'form',
            # 'context': {'active_ids': active_ids, 'active_model': active_model},
            'target': 'new',
        }


class ResetUserPasswordWizard(models.TransientModel):
    _name = 'exhibition.reset_user_password_wizard'
    _description = 'Reset exhibition user password'

    def _get_user(self):
        active_model = self.env.context.get('active_model')
        active_ids = self.env.context.get('active_ids')
        if not active_ids or active_model != 'exhibition.users':
            return False
        return active_ids[0]

    def _get_user_name(self):
        active_model = self.env.context.get('active_model')
        active_ids = self.env.context.get('active_ids')
        if not active_ids or active_model != 'exhibition.users':
            return False
        active_user = self.env[active_model].browse(active_ids)[0]
        return active_user.name

    def _get_user_login(self):
        active_model = self.env.context.get('active_model')
        active_ids = self.env.context.get('active_ids')
        if not active_ids or active_model != 'exhibition.users':
            return False
        active_user = self.env[active_model].browse(active_ids)[0]
        return active_user.login

    user_id = fields.Many2one('exhibition.users', string='目标用户', required=True, default=_get_user)
    name = fields.Char(string='名称', required=True, default=_get_user_name)
    login = fields.Char(string='登录名', required=True, default=_get_user_login)
    new_password = fields.Char('新的密码', default='')

    @api.multi
    def confirm_resetting_password(self):
        for user in self:
            if not user.new_password:
                raise UserError('请填入需要重置的密码')
            user.user_id.sudo().write({'password': user.new_password})
        return {'type': 'ir.actions.act_window_close'}
